package com.example.mystore.dao;

import com.example.mystore.entity.Customer;
import com.example.mystore.utils.LinkMySQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Objects;

public class CustomersDao {
    public static boolean checkEmail(String email){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet res = null;
        boolean check = false;
        try {
            conn = LinkMySQL.getConnection();
            String sql = "select * from customer where email = ?";
            pstmt = Objects.requireNonNull(conn).prepareStatement(sql);
            pstmt.setString(1,email);
            res = pstmt.executeQuery();
            if(res.next()){
                check = true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(res,pstmt,conn);
        }
        return check;
    }
    public static Customer selectCustomer(String email, String password){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet res = null;
        Customer customer = null;
        try {
        conn = LinkMySQL.getConnection();
        String sql = "select * from customer where email = ? and password = ?";
        pstmt = Objects.requireNonNull(conn).prepareStatement(sql);
        pstmt.setString(1,email);
        pstmt.setString(2,password);
        res = pstmt.executeQuery();
                if(res.next()){
                    customer = new Customer
                            (res.getString("name"),res.getString("email"),res.getString("password"),res.getString("address"), res.getString("PAC"),res.getString("phone"),res.getString("fax"));

                }
                 }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(res,pstmt,conn);
        }
        return customer;
    }
    public  static boolean insertCustomers(Customer customer){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int numb = 0;
        try {
            conn = LinkMySQL.getConnection();
            String sql = "insert into customer values(?,?,?,?,?,?,?)";
            pstmt = Objects.requireNonNull(conn).prepareStatement(sql);
            pstmt.setString(1,customer.getName());
            pstmt.setString(2,customer.getEmail());
            pstmt.setString(3,customer.getPassword());
            pstmt.setString(4,customer.getAddress());
            pstmt.setString(5,customer.getPAC());
            pstmt.setString(6,customer.getPhone());
            pstmt.setString(7,customer.getFax());
            numb = pstmt.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(pstmt,conn);
        }
        return numb > 0;
    }
}
